package com.usian.wemedia.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmUserDto;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.common.AppJwtUtil;
import com.usian.wemedia.mapper.WmUserMapper;
import com.usian.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    @Override
    public WmUser findbyname(String name) {
        QueryWrapper<WmUser> Wrapper = new QueryWrapper<>();
        Wrapper.eq("name",name);
        List<WmUser> list = list(Wrapper);
        if (!list.isEmpty() && list !=null){
            return list.get(0);
        }
        return null;
    }

    @Override
    public ResponseResult login(WmUserDto dto) {
        //检查参数
        if (StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getPassword())){
            return  ResponseResult.errorResult(AppHttpCodeEnum.NULL_CANSHU);
        }
        //创建构造器
        QueryWrapper<WmUser> wmUserQueryWrapper = new QueryWrapper<>();
        wmUserQueryWrapper.eq("name",dto.getName());
        List<WmUser> list = list(wmUserQueryWrapper);
        //判断用户是否存在
        if (list.size() ==1 && list !=null){
            WmUser wmUser = list.get(0);
            //md5密码解密
            String pwd = DigestUtils.md5DigestAsHex((dto.getPassword() + wmUser.getSalt()).getBytes());
            //校验密码是否正确
            if (pwd.equals(wmUser.getPassword())){
                //map返回集合
                Map<String, Object> map = new HashMap<>();
                map.put("token", AppJwtUtil.getToken(wmUser.getId().longValue()));
                wmUser.setPassword("");
                wmUser.setSalt("");
                map.put("wuuser",wmUser);
                //返回token
                return ResponseResult.okResult(map);
            }else {
                return  ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }

    }
}
